import React, { Component } from 'react';
import './organize-mgt.css';
import { Button, message, Input, Table, Modal, Breadcrumb } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import LinkButton from '../../components/link-button/linkButton.jsx';
import { reqOrgNameSearch, reqAddOrgInfor, reqEditOrgInfor, reqDeleteOrg, reqOrganListByParentOrgid } from '../../api';
import EditOrganForm from '../../components/Modal/edit-organize-form';
import AddOrganForm from '../../components/Modal/add-organize-form';
import { connect } from 'react-redux';
import { getRolesButtons } from '../../utils/storageUtils';
import editIcon from '../../assets/image/edit.png'
import deleteIcon from '../../assets/image/delete.png'
const { Search } = Input;
const { confirm } = Modal;

class OriganizeMgt extends Component {

  state = {
    organList: [],
    visible: '0',
    loading: false,
    parentId: '',  // 当前需要显示的子组织列表的 父组织Id
    parentName: '',  // 当前需要显示的子组织列表的 父组织Name
    breadcrumb: [],  // 用来显示 组织的层级关系
    roleButtons: [], // 有权限的按钮
  }

  handleNameSearch = async (value) => {   // 2、按姓名模糊查找组织 √
    const org_name = value;
    const org_pid = this.state.parentId;
    //console.log('姓名查找组织参数',org_pid,org_name);
    const result = await reqOrgNameSearch(org_pid, org_name);
    if (result.code === 200) {
      const organList = result.data;
      this.setState({
        organList
      })
    } else {
      message.error(result.data);
    }
  };


  initColumns = () => {
    this.columns = [
      {
        title: '矿区名称', dataIndex: 'org_name', key: 'org_name',
        sorter: {
          compare: (a, b) => a.org_name.localeCompare(b.org_name),
        },
      },
      { title: '矿区联系方式', dataIndex: 'org_contact', key: 'org_contact' },
      { title: '矿区地址', dataIndex: 'org_address', key: 'org_address' },
      { title: '备注', dataIndex: 'org_remark', key: 'org_remark' },
      {
        title: '操作',
        dataIndex: '',
        key: 'action',
        width: 130,
        render: (organInfor) => (
          <span>
            <LinkButton onClick={this.state.roleButtons.indexOf("organization-edit") === -1 ? this.noRightMessage : () => this.editShow(organInfor)}>
              <img src={editIcon} alt="" />
            </LinkButton>
            <LinkButton onClick={this.state.roleButtons.indexOf("organization-delete") === -1 ? this.noRightMessage : () => this.showDeleteConfirm(organInfor)}>
              <img src={deleteIcon} alt="" />
            </LinkButton>
          </span>
        ),
      }, {
        title: '',
        dataIndex: '',
        key: 'action1',
        width: 115,
        render: (organInfor) => (<LinkButton onClick={this.state.roleButtons.indexOf("organization-find-parentId") === -1 ? this.noRightMessage : () => this.getOrganList(organInfor)}>
          <div className='lookBtn'>
            查看子矿区
          </div>
        </LinkButton>),
      },
    ];
  }

  getOrganList = async (organInfor) => {  // 1、获取组织列表(包含子组织列表) √
    var org_pid;
    if (organInfor) {
      org_pid = organInfor.org_id;
      // breadcrumb这部分是处理 左上角的组织层级关系显示功能
      var breadcrumb = [...this.state.breadcrumb];
      var breadId = [];
      breadcrumb.map((item) => {
        breadId.push(item.org_pid);
      })
      if (breadId.indexOf(organInfor.org_id) === -1) {  // 列表中没有他，那就添加进去
        breadcrumb.push({ org_pid: org_pid, org_pname: organInfor.org_name });
      } else {   // 如果有，说明用户在进行返回操作，将后面的都删掉
        const index = breadId.indexOf(organInfor.org_id) + 1;
        breadcrumb.splice(index, breadcrumb.length - index);
      }

      this.setState({
        loading: true,
        parentId: org_pid,
        parentName: organInfor.org_name,
        breadcrumb
      });
    } else {
      org_pid = this.props.user.org.org_id;
      var breadcrumb = [];
      breadcrumb.push({ org_pid: org_pid, org_pname: this.props.user.org.org_name });   // 最高级组织
      this.setState({
        loading: true,
        parentId: org_pid,
        parentName: this.props.user.org.org_name, //最高级组织
        breadcrumb
      });
    }

    const result = await reqOrganListByParentOrgid(org_pid);
    console.log("获取所有组织", result);
    this.setState({ loading: false });
    const organList = result.data;
    this.setState({
      organList
    })
  }

  getroleButtons = () => {  // 获取该模块的有权限的按钮
    getRolesButtons().map((item) => {
      if (item.key === '/orgzanition-mgt') {
        this.setState({
          roleButtons: item.buttons
        })
      }
    })
  }

  noRightMessage = () => {
    message.error("无访问权限！");
  }

  addShow = () => {   //添加组织 弹框
    this.setState({
      visible: '1'
    })
  }
  addOrganInfor = async () => {   // 添加组织 响应函数  √
    this.setState({ visible: '0' })
    // 1、获取输入的数据
    const org_pid = this.state.parentId;
    const org_name = this.formRef.current.getFieldValue('org_name');
    const org_contact = this.formRef.current.getFieldValue('org_contact');
    const org_address = this.formRef.current.getFieldValue('org_address');
    const org_remark = this.formRef.current.getFieldValue('org_remark') ? this.formRef.current.getFieldValue('org_remark') : " ";
    const org_province = this.formRef.current.getFieldValue('org_province');
    //console.log('创建组织参数',org_pid,org_name,org_contact,org_address,org_remark,org_province);
    // 2、发送请求 添加组织
    const result = await reqAddOrgInfor(org_pid, org_name, org_contact, org_address, org_remark, org_province);
    //console.log("创建组织",result);
    if (result.code === 200) {
      message.success("创建成功！");
      // 3、重新获取列表
      const organInfor = {
        org_id: this.state.parentId,
        org_name: this.state.parentName
      }
      this.getOrganList(organInfor);
    } else {
      message.error(result.data);
    }
  }

  editShow = (organInfor) => {   // 编辑组织 弹框
    this.organInfor = organInfor;
    this.setState({
      visible: '2'
    })
  }
  editOrganInfor = async () => {
    this.setState({
      visible: '0'
    })
    // 1、获取输入的数据
    const org_id = this.organInfor.org_id;
    const org_pid = this.organInfor.org_pid;
    const org_name = this.formRef.current.getFieldValue('org_name');
    const org_contact = this.formRef.current.getFieldValue('org_contact');
    const org_address = this.formRef.current.getFieldValue('org_address');
    const org_remark = this.formRef.current.getFieldValue('org_remark');
    console.log('编辑组织', org_id, org_pid, org_name, org_contact, org_address, org_remark)
    // 2、发送请求 添加组织
    const result = await reqEditOrgInfor(org_id, org_pid, org_name, org_contact, org_address, org_remark);
    if (result.code === 200) {
      // 3、重新获取列表
      const organInfor = {
        org_id: this.state.parentId,
        org_name: this.state.parentName
      }
      this.getOrganList(organInfor);
    }
  }

  // 对话框取消按钮
  handleCancel = () => {
    this.setState({
      visible: '0'
    })
  }

  handleDeleteOnOk = async (organInfor) => {  // 删除onOk
    const org_id = organInfor.org_id;
    const org_pid = organInfor.org_pid;
    const result = await reqDeleteOrg(org_id, org_pid);
    if (result.code === 200) {
      const organInfor = {
        org_id: this.state.parentId,
        org_name: this.state.parentName
      }
      this.getOrganList(organInfor);
    }
  };

  showDeleteConfirm = (organInfor) => {   // 删除响应函数
    confirm({
      title: '您确定要删除该矿区吗?',
      icon: <ExclamationCircleOutlined />,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => this.handleDeleteOnOk(organInfor)
    })
  };


  componentWillMount() {   // 为第一次render准备数据
    this.getroleButtons();
    this.initColumns();
  };

  componentDidMount() {  // 发送异步请求
    this.getOrganList();
  }

  render() {
    const { visible, organList, loading, parentName, parentId, breadcrumb, roleButtons } = this.state;
    const organInfor = this.organInfor || {};

    return (
      <div className='origanize-mgt-wrapper'>
        <div className='origanize-mgt-header'>
          <div>
            <span className='origanize-header-search-label'>矿区名称：</span>
            <Search
              className='origanize-header-search'
              placeholder="根据矿区名称搜索"
              enterButton="搜索"
              size="middle"
              onSearch={(value) => this.handleNameSearch(value)}
              disabled={roleButtons.indexOf("organization-find-organizationName") === -1 ? true : false}
            />
            {
              roleButtons.indexOf("organization-create") === -1 ? null : <Button type="primary" className='origanize-header-add' onClick={this.addShow}>创建矿区</Button>
            }
          </div>
          <Breadcrumb separator=">" className="origanize-mgt-breadcrumb">
            {breadcrumb.map((item, index) => {
              return <Breadcrumb.Item onClick={() => this.getOrganList({ org_id: item.org_pid, org_name: item.org_pname })} className="breadcrumb-item">{item.org_pname}</Breadcrumb.Item>
            })}
          </Breadcrumb>
        </div>
        <div className='origanize-mgt-content'>
          <Table
            columns={this.columns}
            dataSource={organList}
            size='middle'
            loading={loading}
            pagination={false}
            locale={{
              cancelSort: '点击取消排序',
              triggerAsc: '点击升序',
              triggerDesc: '点击降序'
            }}
          />

          <Modal
            title="新增矿区信息"
            visible={visible === '1'}
            onOk={this.addOrganInfor}
            onCancel={this.handleCancel}
            okText="确定"
            cancelText="取消"
            destroyOnClose={true}
          >
            <AddOrganForm
              orgParentName={parentName}
              setForm={(formRef) => { this.formRef = formRef }} />
          </Modal>

          <Modal
            title="编辑矿区信息"
            visible={visible === '2'}
            onOk={this.editOrganInfor}
            onCancel={this.handleCancel}
            okText="确定"
            cancelText="取消"
            destroyOnClose={true}
          >
            <EditOrganForm
              orgName={organInfor.org_name}
              orgMobile={organInfor.org_contact}
              orgAddress={organInfor.org_address}
              orgRemark={organInfor.org_remark}
              setForm={(formRef) => { this.formRef = formRef }}
            />
          </Modal>
        </div>
      </div>

    )
  }
}

export default connect(
  state => ({ user: state.user, orgInfo: state.orgInfo }),
  {}
)(OriganizeMgt);